import DeviceInfo from 'react-native-device-info';
import { useEffect,useMemo, useCallback, useRef } from 'react';
import {GQL} from '../network';
import { Keys,Storage } from './storage';
import User from './store/userStore';
import ApolloClient from 'apollo-boost';
import DataCenter from './OneForAll/DataCenter';

const TAG = "数据 :: useAutoSignIn.ts :: \\ ";

interface Props {
    client: any,
    onSuccess?: () => void,
    onFailed?: () => void,
}
const useAutoSignIn: (props:Props) => void = (props:Props) => {
    let {client} = props;
    let onSuccess = props.onSuccess ?? null;
    let onFailed = props.onFailed ?? null;

    const MemomizedClient = useMemo(() => {
        return client;
    },[client])

    async function AutoSignInHandler(){
        let user = await Storage.getItem(Keys.user);
        let token = user?.token ?? null;
        if(!token){ // 没有用户缓存、发起静默登录
            doAutoSignIn()
        }else{//有用户缓存
            //console.log(TAG,"用户数据",user)
            //执行登录操作，更新store
            // DataCenter.User_Core 会执行用户数据恢复操作
        }
    }
    async function doAutoSignIn(){
        const uuid = DeviceInfo.getUniqueId();
        //console.log("发起静默登录，uuid为 : ",uuid)
        //console.log("GQL DOcument ",GQL.autoSignInMutation)
        if(uuid){
            MemomizedClient.mutate({
                mutation: GQL.autoSignInMutation,
                variables: { UUID: uuid },
            }).then( rs => {
                console.log(TAG,"静默登录成功 :",rs);
                const autoSignIn = rs?.data?.autoSignIn ?? {}

                DataCenter.User_SignIn(autoSignIn);
                Storage.setItem(Keys.firstInstall,false);
            }).catch( err => {
                console.log(TAG,"静默登录失败 :",err);
            })
        }else{
            //TODO:获取UUID失败
            console.log("获取UUID失败")
        }
    }

    useEffect(() => {
        AutoSignInHandler();
    },[]);

}

export default useAutoSignIn;